﻿(function () {
    /*-------------------------------
                Variables
    ---------------------------------*/
    var dma = "";
    var user = "";
    var pass = "";
    var vmr = "";
    var role = "";
    var baseurl = "";
    var url = "";
    var username = "";
    var domain = "";
    var refreshtimer = null;
    var current_UUID = "";

    //the flag variable determines what the user sees and has access to.
    //since some APIs require elevated permissions, these options will not be visible 
    //unless the user has the correct level of permissions
    var flag = "";

    /*-------------------------------
            Button Listeners
    ---------------------------------*/
    var $NAV_HOME = document.getElementById('NAV_HOME');
    $NAV_HOME.addEventListener('click', f_nav_home, false);

    var $NAV_VMR = document.getElementById('NAV_VMR');
    $NAV_VMR.addEventListener('click', f_nav_vmr, false);

    var $NAV_CCA = document.getElementById('NAV_CCA');
    $NAV_CCA.addEventListener('click', f_nav_cca, false);

    var $NAV_CONFIG = document.getElementById('NAV_CONFIG');
    $NAV_CONFIG.addEventListener('click', f_nav_config, false);

    var $NAV_ABOUT = document.getElementById('NAV_ABOUT');
    $NAV_ABOUT.addEventListener('click', f_nav_about, false);

    var $Retrieve = document.getElementById('RetrieveSettings');
    $Retrieve.addEventListener('click', f_retrieve, false);

    var $Save = document.getElementById('SaveSettings');
    $Save.addEventListener('click', f_save, false);

    var $Initialize = document.getElementById('InitializeTool');
    $Initialize.addEventListener('click', f_confirmSettings, false);

    var $EnableRefresh = document.getElementById('Enable_Auto');
    $EnableRefresh.addEventListener('click', f_enable_CCA_Refresh, false);

    var $DisableRefresh = document.getElementById('Disable_Auto');
    $DisableRefresh.addEventListener('click', f_disable_CCA_Refresh, false);

    var $Refresh = document.getElementById('Refresh_View');
    $Refresh.addEventListener('click', f_Refresh_View, false);


    /*-------------------------------
            Functions
    ---------------------------------*/
    document.addEventListener('DOMContentLoaded', function () {
        console.log('appLoaded');
        appLoaded();
    });




    function appLoaded() {
        //first load in the stored info if it exists.
        //retrieve();

        //check to see if we need to display the Configuration Required Banner
        checkBanner();
       
    }

    function checkBanner() {

        document.getElementById("configBanner").style.display = 'block';
        disableNavigation();

        if (flag === "advanced") {
            document.getElementById("configBanner").style.display = 'none';
            enableNavigation(flag);
        }
        else if (flag === "basic") {
            document.getElementById("configBanner").style.display = 'none';
            enableNavigation(flag);
        } 
    }

    function enableNavigation(value) {
        if (value === 'advanced') {
            document.getElementById("NAV_VMR").style.display = 'inherit';
        }
        document.getElementById("NAV_CCA").style.display = 'inherit';
    }

    function disableNavigation() {
        document.getElementById("NAV_VMR").style.display = 'none';
        document.getElementById("NAV_CCA").style.display = 'none';
    }

    function processingCredentials() {
        document.getElementById("header").style.display = 'none';
        document.getElementById("content-config").style.display = 'none';
        document.getElementById("Working_Header").style.display = 'block';
        document.getElementById("Working_Body").style.display = 'block';
    }

    function CredentialsProcessed() {
        document.getElementById("header").style.display = 'block';
        document.getElementById("content-config").style.display = 'block';
        document.getElementById("Working_Header").style.display = 'none';
        document.getElementById("Working_Body").style.display = 'none';
    }

    function badCredentials() {
        document.getElementById("configBanner").style.display = 'none';
        document.getElementById("CredentialBanner").style.display = 'inherit';
        setTimeout(function () {
            document.getElementById("CredentialBanner").style.display = 'none';
            checkBanner();
        }, 10000);
    }
    

    function f_retrieve(event) {
        if (event.preventDefault) event.preventDefault();
        event.returnValue = false;
        retrieve();
    }
    function retrieve() {
        chrome.storage.sync.get('PLCMAPI_dma_fqdn', function (value) {
            dma = value.PLCMAPI_dma_fqdn;
            document.getElementById('dma').value = dma;
            console.log("DMA: " + dma);
        });
        chrome.storage.sync.get('PLCMAPI_dma_user', function (value) {
            user = value.PLCMAPI_dma_user;
            document.getElementById('user').value = user;
            console.log("USER: " + user);
        });
        chrome.storage.sync.get('PLCMAPI_dma_pw', function (value) {
            pw = value.PLCMAPI_dma_pw;
            document.getElementById('password').value = pw;
            console.log("PW: " + pw);
        });
        chrome.storage.sync.get('PLCMAPI_dma_vmr', function (value) {
            vmr = value.PLCMAPI_dma_vmr;
            document.getElementById('vmr').value = vmr;
            console.log("VMR: " + vmr);
        });
        chrome.storage.sync.get('PLCMAPI_flag', function (value) {
            flag = value.PLCMAPI_flag
            console.log("FLAG: " + flag);
        });

        
    }

    function f_confirmSettings(){
        if (event.preventDefault) event.preventDefault();
        event.returnValue = false;
        confirmSettings();
    }
    function confirmSettings() {
        dma = document.getElementById('dma').value;
        user = document.getElementById('user').value;
        pw = document.getElementById('password').value;
        vmr = document.getElementById('vmr').value;

        var res = user.split("\\");
        domain = res[0];
        username = res[1];
        console.log(domain);
        console.log(username);

        getDMARole();
    }

    function f_save() {
        if (event.preventDefault) event.preventDefault();
        event.returnValue = false;
        confirmSettings();
        save();
    }
    function save() {
        dma = document.getElementById('dma').value;
        user = document.getElementById('user').value;
        pw = document.getElementById('password').value;
        vmr = document.getElementById('vmr').value;

        chrome.storage.sync.set({ 'PLCMAPI_dma_fqdn': dma }, function () {
        });
        chrome.storage.sync.set({ 'PLCMAPI_dma_user': user }, function () {
        });
        chrome.storage.sync.set({ 'PLCMAPI_dma_pw': pw }, function () {
        });
        chrome.storage.sync.set({ 'PLCMAPI_dma_vmr': vmr }, function () {
        });
        chrome.storage.sync.set({ 'PLCMAPI_flag': flag }, function () {
        });
    }

    function f_enable_CCA_Refresh() {
        if (event.preventDefault) event.preventDefault();
        event.returnValue = false;
        enable_CCA_Refresh();
    }
    function enable_CCA_Refresh() {
        document.getElementById("Refresh_View").style.display = "none";
        document.getElementById("Enable_Auto").style.display = "none";
        document.getElementById("Disable_Auto").style.display = "inline";
        refreshtimer = setInterval(function () {timer(); }, 3000);
    }

    function timer(){
        console.log("timer")
    }

    function f_disable_CCA_Refresh() {
        if (event.preventDefault) event.preventDefault();
        event.returnValue = false;
        disable_CCA_Refresh();
    }
    function disable_CCA_Refresh() {
        document.getElementById("Refresh_View").style.display = "inline";
        document.getElementById("Enable_Auto").style.display = "inline";
        document.getElementById("Disable_Auto").style.display = "none";
        clearInterval(refreshtimer);
    }

    function f_Refresh_View() {
        getPart_S1(vmr);
    }

    function f_nav_home() {
        document.getElementById("content-home").style.display = "block";
        document.getElementById("content-vmr").style.display = "none";
        document.getElementById("content-cca").style.display = "none";
        document.getElementById("content-config").style.display = "none";
        document.getElementById("content-about").style.display = "none";
    }

    function f_nav_vmr() {
        document.getElementById("content-home").style.display = "none";
        document.getElementById("content-vmr").style.display = "block";
        document.getElementById("content-cca").style.display = "none";
        document.getElementById("content-config").style.display = "none";
        document.getElementById("content-about").style.display = "none";
    }

    function f_nav_cca() {
        document.getElementById("content-home").style.display = "none";
        document.getElementById("content-vmr").style.display = "none";
        document.getElementById("content-cca").style.display = "block";
        document.getElementById("content-config").style.display = "none";
        document.getElementById("content-about").style.display = "none";
    }

    function f_nav_config() {
        document.getElementById("content-home").style.display = "none";
        document.getElementById("content-vmr").style.display = "none";
        document.getElementById("content-cca").style.display = "none";
        document.getElementById("content-config").style.display = "block";
        document.getElementById("content-about").style.display = "none";
    }

    function f_nav_about() {
        document.getElementById("content-home").style.display = "none";
        document.getElementById("content-vmr").style.display = "none";
        document.getElementById("content-cca").style.display = "none";
        document.getElementById("content-config").style.display = "block";
        document.getElementById("content-about").style.display = "none";
    }

    function make_base_auth(user, password) {
        var tok = user + ':' + password;
        var hash = Base64.encode(tok);
        return "Basic " + hash;
    }

    function initialize() {
        dma = "";
        user = "";
        pass = "";
        vmr = "";
        role = "";
        flag = "";
        baseurl = "";
        url = "";
    }

    function getPart_S1(room) {
        var UUID = ""
        baseurl = "https://" + dma + ":8443";
        url = baseurl + '/api/rest/conferences/?conference-room-identifier=' + room;
        console.log(url);

        var xhr = new XMLHttpRequest();
        xhr.open('GET', url);

        auth = make_base_auth(user, pw);

        xhr.setRequestHeader("Authorization", auth);
        //xhr.withCredentials = true;
        xhr.setRequestHeader("Accept", "application/vnd.plcm.plcm-conference-list+xml");

        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    var response = xhr.responseXML.querySelectorAll("conference-identifier");
                    var cid = ""
                    if (response.length === 0) {
                        //no on going conferences...do something here...
                    }
                    else {
                        for (var n = 0; n < response.length; n++) {
                            if (cid == "") {
                                cid = response[n].textContent;
                            }
                            else {
                                cid = cid + ", " + response[n].textContent;
                            }
                            //list_part(dma, login, pass, name);
                            UUID = cid;
                            console.log("conf_id" + UUID);
                        }

                    }
                    current_UUID = UUID;
                    getConfParticipants_S2(UUID);
                }
                if (xhr.status === 403) {
                }
            } else {
                console.error(xhr.readyState + " " + xhr.status);
            }
        };

        

    }

    function getConfParticipants_S2(_UUID) {
        console.log("S2: " + _UUID);
    }

    function getDMARole() {
        baseurl = "https://" + dma + ":8443";
        url = baseurl + "/api/rest/users?username=" + username;
        console.log(url);

        var xhr = new XMLHttpRequest();
        xhr.open('GET', url);

        auth = make_base_auth(user, pw);

        xhr.setRequestHeader("Authorization", auth);
        //xhr.withCredentials = true;

        //required for backwards compatability.
        xhr.setRequestHeader("Accept", "application/vnd.plcm.plcm-user-list+xml");

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    flag = "advanced";
                    //I don't need to parse to know that the user has advanced level credentials 
                    //this is because I would get a 403 error if they are just regular users
                    //getting a 200 status code means that I authenticated and was successful at getting
                    //the information which implies i have Provisioner level access or greater.
                    //var items = xhr.responseXML.getElementsByTagName("name");
                    checkBanner();
                }
                if (xhr.status === 403) {
                    flag = "basic";
                    checkBanner();
                }

                if (xhr.status === 401) {
                    flag = "";
                    badCredentials();
                }
                CredentialsProcessed();
            } else {

                console.error(xhr.readyState + " " + xhr.status);
            }
        };

        xhr.send();

        processingCredentials();

    }

})();